/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unipiloto.edu.co.auth.service.tracker;

import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;
import unipiloto.edu.co.auth.service.api.UserAuthenticacionService;

/**
 *
 * @author David
 */
public class ServiceLocator {

    private ServiceTracker stAuth;

    public ServiceLocator(BundleContext context) {
        stAuth = new ServiceTracker(context, UserAuthenticacionService.class.getName(), null);
        stAuth.open();
    }

    /**
     * Looks up a service and returns
     * @param timeout
     * @return
     */
    public UserAuthenticacionService getUserAuthenticacionService(long timeout) throws ServiceUnavailableException {
        UserAuthenticacionService service = null;
        try {
            service = UserAuthenticacionService.class.cast(timeout == -1 ? stAuth.getService() : stAuth.waitForService(timeout));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (service == null) {
            throw new ServiceUnavailableException();
        }
        return service;
    }

    public void close() {
        stAuth.close();
    }

    public static class ServiceUnavailableException extends Exception {
    }
}
